// pages/passage/passage.js
const QQMapWX = require("../../../utils/qqmap-wx.js");
var distance = new QQMapWX({
  key: "DN6BZ-YKMRP-EUHDE-LEBIO-YR736-SRBUI" // 必填
});

const app = getApp();
var getlist = function (that) {
  // var drivers = app.getApi.drivers;
  // var company = wx.getStorageSync("COMPANY");
  var drivers = wx.getStorageSync("DRIVERS");
  wx.showLoading({
    title: "加载中"
  });
  app.getApi.request(

    that.data.url, {
      location: {
        longitude: wx.getStorageSync("longitude"),
        latitude: wx.getStorageSync("latitude"),
        locationAddress: wx.getStorageSync("address")
      },
      driversOrdersStatus: that.data.navIndex,
      drivers: {
        id: drivers.id,
        name: drivers.name,
        tel: drivers.tel
      },
      ordersSearch: {
        IsGetGoodsInfo: true
      },
      pageIndex: that.data.pageIndex,
      pageSize: 10
    },
    "POST",
    res => {
      wx.hideLoading();
      if (res.data.responseCode == 1000) {
        //列表数据
        var ordersList = [];
        if (res.data.obj.length > 0) {
          for (let i = 0; i < res.data.obj.length; i++) {
            res.data.obj[i] = Object.assign(res.data.obj[i], { checked: false })
            var orderObj = {};
            if (res.data.obj[i].orders.beginTime) {
              res.data.obj[i].orders.beginTime = res.data.obj[i].orders.beginTime.substring(5, 10).replace('-', '.')
            }

            if (res.data.obj[i].orders.endTime) {
              res.data.obj[i].orders.endTime = res.data.obj[i].orders.endTime.substring(5, 10).replace('-', '.')
            }

            if (res.data.obj[i].orders.beginTimeRang) { //修改取货时间格式
              res.data.obj[i].orders.beginTimeRang = res.data.obj[i].orders.beginTimeRang.substring(0, 11)
            }
            if (res.data.obj[i].orders.endTimeRang) { //修改送货时间格式

              res.data.obj[i].orders.endTimeRang = res.data.obj[i].orders.endTimeRang.substring(0, 11)

            }
            orderObj.id = res.data.obj[i].orders.id;
            orderObj.orderNumber = res.data.obj[i].orders.orderNumber;

            if (res.data.obj[i].orders.consignee) {
              orderObj.consigneeCity =
                res.data.obj[i].orders.consignee.consigneeCity;
            }

            orderObj.endTime = res.data.obj[i].orders.endTime;
            ordersList.push(orderObj);
          }
        }
        that.setData({
          items: that.data.items.concat(res.data.obj),
          onSh: true
        });
        if (that.data.pageIndex > 1 && res.data.obj.length == 0) {
          that.setData({
            isAll: true
          });
        }
        if (that.data.pageIndex == 1 && res.data.obj.length == 0) {
          that.setData({
            noData: true
          });
        }
      } else {
        wx.showToast({
          title: '请求失败',
          icon: 'loading',
          duration: 2000
        });
      }
      wx.stopPullDownRefresh()
      // if(res.data.)
    },
    res => { }
  );
};

var orderList = function (that) {
  //已完成的订单数据
  // var drivers = app.getApi.drivers;
  var drivers = wx.getStorageSync("DRIVERS");
  // var drivers = app.getApi.drivers;
  wx.showLoading({
    title: "加载中"
  });
  app.getApi.request(
    "/api/Orders/FinishedList", {
      driver: {
        id: drivers.id,
        name: drivers.name,
        tel: drivers.tel
      },
      location: {
        longitude: wx.getStorageSync("longitude"),
        latitude: wx.getStorageSync("latitude"),
        locationAddress: wx.getStorageSync("address")
      },
      ordersSearch: {
        IsGetGoodsInfo: true
      },
      pageIndex: that.data.pageIndex,
      pageSize: 10
    },
    "POST",
    res => {
      wx.hideLoading();
      if (res.data.responseCode == 1000) {
        //列表数据
        if (res.data.obj.length > 0) {
          for (let i = 0; i < res.data.obj.length; i++) {
            if (res.data.obj[i].beginTime) {
              res.data.obj[i].beginTime = res.data.obj[i].beginTime.substring(5, 10).replace('-', '.')
            }

            if (res.data.obj[i].endTime) {
              res.data.obj[i].endTime = res.data.obj[i].endTime.substring(5, 10).replace('-', '.')
            }

            if (res.data.obj[i].beginTimeRang) { //修改取货时间格式
              res.data.obj[i].beginTimeRang = res.data.obj[i].beginTimeRang.substring(0, 11)
            }
            if (res.data.obj[i].endTimeRang) { //修改送货时间格式

              res.data.obj[i].endTimeRang = res.data.obj[i].endTimeRang.substring(0, 11)

            }
          }
        }
        that.setData({
          items: that.data.items.concat(res.data.obj),
          onSh: true
        });

        if (that.data.pageIndex > 1 && res.data.obj.length == 0) {
          that.setData({
            isAll: true
          });
        }
        if (that.data.pageIndex == 1 && res.data.obj.length == 0) {
          that.setData({
            noData: true
          });
        }
      } else {
        wx.showToast({
          title: '请求失败',
          icon: 'loading',
          duration: 2000
        });
      }
      wx.stopPullDownRefresh()
    },
    res => { }
  );
};

Page({
  /**
   * 页面的初始数据
   */
  data: {
    navIndex: 2,
    pageIndex: 1,
    items: [],
    isAll: false,
    noData: false,
    hidden: false,
    Pullcount: 0,
    url: "api/DriversOrders/List",
    onSh: false, //首次数据加载是否完成
    takedOrderCount: '', //待取件
    pickUpedOrderCount: '', //待入库
    finishedOrderCount: '', //已完成
    isCar: false,
    isCal: false,
    id: '',
    driversordersstatusname: '',
    currIndex: 0,
    itemNums:0,
    nums:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {

    var drivers = wx.getStorageSync("DRIVERS");

    var that = this;
    that.setData({
      items: [],
      isAll: false,
      noData: false,
      hidden: false,
      Pullcount: 0,
      onSh: false,
      pageIndex: 1
    });
    if (that.data.navIndex == 6) {
      orderList(that);
    } else {
      getlist(that);
    }





    app.getApi.request(
      "/api/DriversOrders/Get3StatusList", {
        drivers: {
          id: drivers.id,
          name: drivers.name,
          tel: drivers.tel
        },
        location: {
          longitude: wx.getStorageSync("longitude"),
          latitude: wx.getStorageSync("latitude"),
          locationAddress: wx.getStorageSync("address")
        },
        pageIndex: that.data.pageIndex,
        pageSize: 10
      },
      "POST",
      res => {
        wx.hideLoading();
        if (res.data.responseCode == 1000) {
          //列表数据
          that.setData({
            takedOrderCount: res.data.obj.takedOrderCount,
            pickUpedOrderCount: res.data.obj.pickUpedOrderCount,
            finishedOrderCount: res.data.obj.finishedOrderCount
          })

        } else {
          wx.showToast({
            title: '请求失败',
            icon: 'loading',
            duration: 2000
          });
        }
      },
    );

  },

  onReachBottom() {
    var that = this;
    if (!that.data.isAll && that.data.Pullcount == 0 && that.data.onSh) {
      that.setData({
        pageIndex: that.data.pageIndex + 1
      });
      that.loadMore = true;
      if (that.data.navIndex == 6) {
        orderList(that);
      } else {
        getlist(that);
      }
    } else {
      that.hidden = true;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  nav(e) { //切换tab
    var that = this,
      url = "";
    if (e.currentTarget.dataset.index == 2) {
      url = "api/DriversOrders/List";
    }
    if (e.currentTarget.dataset.index == 4) {
      url = "api/DriversOrders/List";
    }
    that.setData({
      navIndex: Number(e.currentTarget.dataset.index),
      items: [],
      url: url,
      isAll: false,
      noData: false,
      hidden: false,
      Pullcount: 0,
      pageIndex: 1
    });
    if (e.currentTarget.dataset.index == 6) {
      orderList(that);
    } else {
      getlist(that);
    }
  },
  order(e) { // 跳转取件
    var item = JSON.stringify(e.currentTarget.dataset.item);
    app.globalData.driversOrders = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: "../take/take?id=" +
      e.currentTarget.dataset.id +
      "&item=" +
      item
    });
  },
  deliveryDetail(e) { //派单详情

    var item = JSON.stringify(e.currentTarget.dataset.item);
    app.globalData.driversOrders = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: "../deliveryDetail/deliveryDetail?id=" +
      e.currentTarget.dataset.id +
      "&item=" +
      item
    });
  },
  achieveDetails(e) { //完成订单详情
    var item = JSON.stringify(e.currentTarget.dataset.item);
    app.globalData.driversOrders = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: "../achieveDetails/achieveDetails?id=" +
      e.currentTarget.dataset.id +
      "&item=" +
      item
    });
  },
  /**
   *拨打电话
   */
  makePhoneCall(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.number
    });
  },
  toMap: function (e) {
    //进入地图页面
    let address = e.currentTarget.dataset.address;

    distance.geocoder({
      address: address,
      success: function (res) {
        if (res.result) {
          // that.setData({
          //     location: res.result
          // })
          wx.openLocation({
            latitude: parseFloat(res.result.location.lat),
            longitude: parseFloat(res.result.location.lng),
            scale: 18,
            address: address
          });
        } else {
          that.setData({
            location: null
          });
        }
      },
      fail: function (res) {

      },
      complete: function (res) {

      }
    });
  },
  onPullDownRefresh: function () {
    this.onLoad()
  },
  toSMS() { //发送短信
    wx.showToast({
      title: ' 功能正在开发',
      icon: 'loading',
      duration: 2000
    });
  },
  cal() {
    var that = this
    that.setData({
      isCal: false
    })
  },
  sub(id, driversOrdersStatusName) {
    var that = this
    var drivers = wx.getStorageSync("DRIVERS");
    var company = wx.getStorageSync("COMPANY");
    app.getApi.request(
      "/api/Vehicles/vehicledeparture", {
        drivers: {
          id: drivers.id,
          name: drivers.name,
          tel: drivers.tel
        },
        "driversOrders": {
          "id": that.data.id,
          "driversOrdersStatus": 1,
          "driversOrdersStatusName": that.data.driversOrdersStatusName,
          "pickUpNums": 0
        }

      },
      "POST",
      data => {
        var that = this
        if (data.statusCode == "200") {
          that.setData({
            isCar: true,
            isCal: false
          })
        }
      },

    );
  },
  goCar(e) { //发车
    var that = this
    that.setData({
      isCal: true,
      id: e.currentTarget.dataset.id,
      driversordersstatusname: e.currentTarget.dataset.driversordersstatusname
    })
  },
  changeCar() { //换车
    wx.navigateTo({
      url: '../myCart/myCart',
    })
  },
  toindex() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  topassage() {
    wx.redirectTo({
      url: '../passage/passage',
    })
  },


  // tab切换
  tabChange(e) {
    let _datasetId = e.target.dataset.id;
    this.setData({
      currIndex: _datasetId
    });
  },

  bindOrder() {
    console.log('订单');
  },
  bindLoadCar() {
    console.log('装车 | 扫描');
  },
  itemCheck(e) {//单选
    var that = this
    var checked = e.currentTarget.dataset.id;
    var items = [];
    for (var i = 0; i < that.data.items.length; i++) {
      if (checked.indexOf(that.data.items[i].id.toString()) !== -1) {
        if (that.data.items[i].checked == false) {
          items[i] = Object.assign( that.data.items[i], { checked: true });
        } else {
          items[i] = Object.assign( that.data.items[i], { checked: false });
        }
      } else {
        items[i] = Object.assign(that.data.items[i]);
      }
    }
    var itemNums = 0
    var nums = 0
    var newlist =[]
    for (var i = 0; i < items.length; i++) {
      if (items[i].checked == true) {
        newlist.push(items[i])
       
      }
    }
    for (var j = 0; j < newlist.length;j++){
      for (var k = 0; k < newlist[j].orders.orderGoodInfosList.length;k++){
        nums += newlist[j].orders.orderGoodInfosList[k].nums
      }
    }
    itemNums = newlist.length
    that.setData({
      itemNums: itemNums,
      nums: nums,
      items: items
    })
  },
  join(){//加入清单
  var that =this
    var newlist=[]
    for (var i = 0; i < that.data.items.length; i++) {
      if (that.data.items[i].checked == true) {
        newlist.push(that.data.items[i])

      }
    }      

    var item = JSON.stringify(newlist);
    wx.redirectTo({
      url: "../take/take?item=" + item     
    })

  }
});